/*
 ============================================================================
 Name		: AppSettings.cpp
 Author	  : 
 Version	 : 1.0
 Copyright   : Your copyright notice
 Description : CAppSettings implementation
 ============================================================================
 */

#include "AppSettings.h"
#include <eikenv.h>

_LIT(KSettingsFile, "auto_keylock_app_settings.dat");
#define KDefaultAutoKeyLock ETrue
#define KDefaultAutoStart ETrue
#define KDefaultLapseTime 10

CAppSettings::CAppSettings()
	{
	// No implementation required
	}

CAppSettings::~CAppSettings()
	{
	}

CAppSettings* CAppSettings::NewLC()
	{
	CAppSettings* self = new (ELeave) CAppSettings();
	CleanupStack::PushL(self);
	self->ConstructL();
	return self;
	}

CAppSettings* CAppSettings::NewL()
	{
	CAppSettings* self = CAppSettings::NewLC();
	CleanupStack::Pop(); // self;
	return self;
	}

void CAppSettings::ConstructL()
	{
    User::LeaveIfError(CEikonEnv::Static()->FsSession().CreatePrivatePath( EDriveC ) );
    User::LeaveIfError(CEikonEnv::Static()->FsSession().PrivatePath(iSettingsFile));
    iSettingsFile += KSettingsFile;	
	}

void CAppSettings::ExternalizeSettingsDataL()
	{
    RFileWriteStream writeStream;
    TInt error = writeStream.Open(CEikonEnv::Static()->FsSession(), iSettingsFile, EFileWrite);
    // Setting file did not exist, create one.
    if (error != KErrNone)
        {
        User::LeaveIfError(writeStream.Create(CEikonEnv::Static()->FsSession(), iSettingsFile, EFileWrite));
        }
    writeStream.PushL();
    SaveL(writeStream);
    writeStream.CommitL();
    writeStream.Pop();
    writeStream.Release();	
	}

void CAppSettings::InternalizeSettingsDataL()
	{
    RFileReadStream readStream;
    TInt error = readStream.Open(CEikonEnv::Static()->FsSession(), iSettingsFile, EFileRead);
    TInt internalizationError = KErrNone;
    // If file existed, try to read settings.
    if (error == KErrNone)
        {
        TRAP(internalizationError, LoadL(readStream);)
        }
    else
        {
        // Use default values in first time when no 
        // setting file exists
        SetDefaultValues();
        }
    readStream.Release();
 
    // Reading failed, settings file might be corrupted.    
    if (internalizationError != KErrNone)
        {
        User::LeaveIfError(CEikonEnv::Static()->FsSession().Delete(iSettingsFile));
        }	
	}

void CAppSettings::LoadL(RReadStream& aStream)
	{
	iAutoKeyLock = aStream.ReadInt8L();
	iAutoStart = aStream.ReadInt8L();
	iLapseTime = aStream.ReadInt8L();
	}

void CAppSettings::SaveL(RWriteStream& aStream) const
	{
	aStream.WriteInt8L(iAutoKeyLock);
	aStream.WriteInt8L(iAutoStart);
	aStream.WriteInt8L(iLapseTime);
	}

void CAppSettings::SetDefaultValues()
	{
	iAutoKeyLock = KDefaultAutoKeyLock;
	iAutoStart = KDefaultAutoStart;
	iLapseTime = KDefaultLapseTime;
	}
